#!/usr/bin/python3
# coding=utf-8

# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# This file is a part of the CANN Open Software.
# Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# ======================================================================================================================
import os
import sys
import logging

import numpy as np

IS_OUTPUT_TXT = False


class MatmulGenData:
    def __init__(self, m, n, k, b, is_trans_a, is_trans_b, is_bias, data_type_str):
        self.m = m
        self.n = n
        self.k = k
        self.b = b
        self.is_trans_a = is_trans_a
        self.is_trans_b = is_trans_b
        self.is_bias = is_bias
        self.data_type_str = data_type_str


    def gen_golden_data_int4_int32(self, work_dir, dst_type=np.int32):
        src_type = np.int8 # two int4 element combine into one int8 element
        x1_shape = [self.k, self.m] if self.is_trans_a else [self.m, self.k]
        x2_shape = [self.n, self.k] if self.is_trans_b else [self.k, self.n]
        # generate x1_gm
        x1_gm = np.random.randint(-5, 5, x1_shape).astype(src_type)
        m_size, k_size = x1_shape[0], x1_shape[1]
        x1_gm_int4 = np.zeros(shape=[m_size, k_size // 2]).astype(src_type)
        for i in range(m_size):
            for j in range(k_size):
                if j % 2 == 0:
                    x1_gm_int4[i][j // 2] = (x1_gm[i][j + 1] << 4) + (x1_gm[i][j] & 0x0f)
        # generate x2_gm
        x2_gm = np.random.randint(-5, 5, x2_shape).astype(src_type)
        k_size, n_size = x2_shape[0], x2_shape[1]
        x2_gm_int4 = np.zeros(shape=[k_size, n_size // 2]).astype(src_type)
        for i in range(k_size):
            for j in range(n_size):
                if j % 2 == 0:
                    x2_gm_int4[i][j // 2] = (x2_gm[i][j + 1] << 4) + (x2_gm[i][j] & 0x0f)

        if self.is_bias:
            bias_gm = np.random.randint(-5, 5, [1, self.n]).astype(dst_type)
            y_gm = (np.matmul(x1_gm.astype(dst_type), x2_gm.astype(dst_type))\
                + bias_gm.astype(dst_type)).astype(dst_type)
        else:
            y_gm = np.matmul(x1_gm.astype(dst_type), x2_gm.astype(dst_type)).astype(dst_type)

        x1_gm_int4.tofile(work_dir + "/input/x1_gm.bin")
        x2_gm_int4.tofile(work_dir + "/input/x2_gm.bin")
        y_gm.tofile(work_dir + "/output/golden.bin")
        if self.is_bias:
            bias_gm.tofile(work_dir + "/input/bias_gm.bin")

        if IS_OUTPUT_TXT:
            np.savetxt(work_dir + "/input/x1_gm.txt", x1_gm_int4.flatten(), fmt='%f', newline='\n')
            np.savetxt(work_dir + "/input/x2_gm.txt", x2_gm_int4.flatten(), fmt='%f', newline='\n')
            np.savetxt(work_dir + "/output/golden.txt", y_gm.flatten(), fmt='%f', newline='\n')
            if self.is_bias:
                np.savetxt(work_dir + "/input/bias_gm.txt", bias_gm.flatten(), fmt='%f', newline='\n')
        return 0


    def gen_golden_data(self, work_dir):
        if self.data_type_str == "int4_int32":
            self.gen_golden_data_int4_int32(work_dir)
        else:
            logging.info("[ERROR] can't support data type %s" % (self.data_type_str))
            return -1
        return 0


    def gen_fake_golden_data(self, work_dir):
        data_type_bytes_ab = 1 / 2  # int4
        data_type_bytes_c = 4       # int32

        file_byte = int(self.m * self.k * data_type_bytes_ab)
        with open(work_dir + "/input/x1_gm.bin", 'wb') as file:
            file.truncate(file_byte)

        file_byte = int(self.k * self.n * data_type_bytes_ab)
        with open(work_dir + "/input/x2_gm.bin", 'wb') as file:
            file.truncate(file_byte)

        if self.is_bias:
            file_byte = 1 * self.n * data_type_bytes_c
            with open(work_dir + "/input/bias_gm.bin", 'wb') as file:
                file.truncate(file_byte)
